package com.lulu.baselib.api.converter;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Author: XuChang
 * Date: 2019/8/13 10:53
 * Description:
 * History:
 */
public class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private final Gson mGson;
    private final TypeAdapter<T> mAdapter;

    public MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.mAdapter = adapter;
    }

    @Override
    public T convert(@NonNull ResponseBody value) throws IOException {
        String response = value.string();
        //后台有时候data，会作为空数组传递过来，转化为null对象，防止解析异常
        JsonObject asJsonObject = new JsonParser().parse(response).getAsJsonObject();
        if (asJsonObject.has("data") && asJsonObject.get("data").isJsonArray()) {
            if (asJsonObject.getAsJsonArray("data").size() == 0){
                asJsonObject.remove("data");
                response = asJsonObject.toString();
            }
        }

        MediaType mediaType = value.contentType();
        Charset charset = mediaType != null ? mediaType.charset(UTF_8) : UTF_8;
        ByteArrayInputStream bis = new ByteArrayInputStream(response.getBytes());
        InputStreamReader reader = new InputStreamReader(bis, charset);
        JsonReader jsonReader = mGson.newJsonReader(reader);
        try {
            return mAdapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
